package com.zzzzzz.topic.web;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zzzzzz.core.web.BaseController;
import com.zzzzzz.topic.model.AddTopicForm;
import com.zzzzzz.topic.model.Topic;
import com.zzzzzz.topic.service.TopicService;

@Controller
public class TopicController extends BaseController {

	@Resource
	private TopicService topicService;

	@RequiresUser
	@RequestMapping(value = "/topic/add", method = RequestMethod.GET)
	public String viewAdd(Model model, @ModelAttribute AddTopicForm addTopicForm) {
		model.addAttribute("cur", "add");
		return "topic/add";
	}

	@RequiresUser
	@RequestMapping(value = "/topic/add", method = RequestMethod.POST)
	public String processAdd(Model model, @ModelAttribute AddTopicForm addTopicForm, BindingResult result, HttpServletRequest request) throws Exception {
		try {
			topicService.add(addTopicForm, findCurrentUser());
			
			return "redirect:/topic/category/" + addTopicForm.getCategory();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e; // handle by Spring
		}
	}

	@RequestMapping(value = "/topic/category/{categoryLb}", method = RequestMethod.GET)
	public String viewCategory(Model model, @PathVariable String categoryLb) {
		model.addAttribute("cur", "explore");
		
		List<Topic> topicList = topicService.findByCategoryLb(categoryLb, 0, 100, false);
		model.addAttribute("topicList", topicList);
		
		return "topic/zi";
	}
	
    
	private static final Logger logger = LoggerFactory.getLogger(TopicController.class);
	
}
